//
//  Y2Encrypt.m
//  Pods-Y2Common_Example
//
//  Created by Mac on 2021/5/31.
//

#import "Y2Encrypt.h"
#import "Y2Common/Y2Category.h"

@implementation Y2Encrypt

+ (NSString *) signWithMD5:(NSDictionary *)dict key:(NSString *)key{
    NSString *normalizedString = [Y2Encrypt generateNormalizedStringWithDict:dict key:key];
    NSString *string = [NSString stringWithFormat:@"%@%@%@", key, normalizedString, key];
    return [string md5];
}

+ (NSString *) signWithRSA:(NSDictionary *)dict Key:(NSString *)key{
    NSString *jsonString = [dict jsonToString];
    NSString *result = [NSString encrypt:jsonString PublicKey:key];
    return result;
}

+ (NSString *)generateNormalizedStringWithDict:(NSDictionary *)dict key:(NSString *)key {
    NSArray *allKeys = [dict allKeys];
    NSArray *sortKeys = [allKeys sortedArrayUsingSelector:@selector(compare:)];
    
    NSString *string = @"";
    for (NSString *k in sortKeys) {
        if ([k isEqual:key]) { continue; }
        NSString *v = [dict objectForKey:k];
        NSString *base64Value = [v base64String];
        NSString *portionString = [NSString stringWithFormat:@"%@=%@", k, base64Value];
        string = [string stringByAppendingString:portionString];
    }
    return string;
}


@end
